package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import Models.Wearhouse;

public class WearhousePresenter {
	public ArrayList<Wearhouse> tryJSONParseArray(String input){
		ArrayList<Wearhouse> warehouses = new ArrayList<Wearhouse>();
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonAllObjects = jsonObj.getJSONObject("wearhouses");
				if(!jsonAllObjects.isNull("wearhouse")){
					Object item = jsonAllObjects.get("wearhouse");
					if(item instanceof JSONArray){
						JSONArray jArray = (JSONArray)item;
						for(int i=0; i < jArray.length(); i++){
							JSONObject jObject = jArray.getJSONObject(i);
							warehouses.add(createWarehouseFromJSONObject(jObject));
						}
					} else {
						JSONObject jObject = (JSONObject)item;
						warehouses.add(createWarehouseFromJSONObject(jObject));
					}
				}
			return warehouses;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Wearhouse tryJSONParse(String input){
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonHop = jsonObj.getJSONObject("wearhouse");
			Wearhouse warehouse = createWarehouseFromJSONObject(jsonHop);
			return warehouse;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public Wearhouse createWarehouseFromJSONObject(JSONObject jsonWH){
		Wearhouse warehouse = new Wearhouse();
		try{
			warehouse.setDescription(jsonWH.getString("WHDesc"));
			warehouse.setID(jsonWH.getInt("wearhouseID"));
			warehouse.setLocation(jsonWH.getString("WHLoc"));
			warehouse.setWHResaleable(jsonWH.getBoolean("WHResalable"));
			return warehouse;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(Wearhouse item){
		try{
			JSONObject json = new JSONObject();
			json.put("WHDesc", item.getDescription());
			json.put("WHLoc", item.getLocation());
			json.put("WHResalable", item.getWHResaleable());
			json.put("wearhouseID", item.getID());
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
